package minix.components;

import java.sql.Blob;
import java.util.regex.Pattern;

import minix.entities.Bilde;
import minix.entities.Profil;

import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.hibernate.Session;
import org.hibernate.lob.BlobImpl;
import org.slf4j.Logger;

public class Filopplaster {
	@Property
	private UploadedFile file;
	@Property
	private Bilde bilde;
	@InjectComponent
	private Form bildeopplaster;
	@Inject
	private Logger logger;
	@Inject
	private Session session;
	@Parameter(required = true, allowNull = false)
	private Profil profil;

	protected boolean erGyldigFiltype(String string) {
		Pattern pattern = Pattern.compile("[.]");
		String[] result = pattern.split(string);
		String type = result[result.length - 1];
		type = type.toLowerCase();
		if (type.equals("jpg") || type.equals("gif") || type.equals("png"))
			return true;
		return false;
	}

	@Log
	@CommitAfter
	public void onSubmitFromBildeopplaster() throws Exception {
		if (!erGyldigFiltype(file.getFileName()))
			bilde = new Bilde();
		bilde.setBildetekst(file.getFileName());
		Blob blob = new BlobImpl(file.getStream(), (int) file.getSize());
		bilde.setData(blob);
		int sistePunktumPosisjon = file.getFileName().lastIndexOf(".");
		logger.debug(sistePunktumPosisjon + "");
		if (sistePunktumPosisjon >= 0) {

			bilde.setEndelse(file.getFileName().subSequence(sistePunktumPosisjon + 1, file.getFileName().length())
					.toString());
			bilde.setType(file.getContentType());
			profil.addBilde(bilde);
			session.saveOrUpdate(bilde);
			session.saveOrUpdate(profil);
			return;
		}
		throw new Exception("Filen var ikke av typen jpg, png eller tif");
	}

	public Profil getProfil() {
		return profil;
	}

	public void setProfil(Profil profil) {
		this.profil = profil;
	}
}
